package org.cmind.soap.android.response;

import java.io.IOException;
import java.io.StringReader;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.util.EntityUtils;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;

/**
 * Simple string to XML converter. To get Document use {@link #getXml()}
 * 
 * @author marcin
 * 
 */
public class SimpleResponseHandler implements ResponseHandler<String> {

    private Document xml;

    @Override
    public String handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
        DocumentBuilderFactory factory;

        try {

            HttpEntity entity = response.getEntity();
            String xmlAsString = EntityUtils.toString(entity);
            DocumentBuilder builder;

            factory = DocumentBuilderFactory.newInstance();
            StringReader sr = new StringReader(xmlAsString);
            InputSource is = new InputSource(sr);
            builder = factory.newDocumentBuilder();

            xml = builder.parse(is);

        } catch (Exception e) {
            throw new IOException(e);
        }
        return null;
    }

    /**
     * Returns response converted to xml.
     * 
     * @return
     */
    public Document getXml() {
        return xml;
    }

}
